package com.hejing.反射的应用;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * ClassName: Reflectest01
 * Package: com.hejing.反射的应用
 * Description:
 *      体会反射的动态性
 *
 * @Author: HeJing
 * @Create: 2023-06-04 21:39
 * @Version: 1.0
 */
public class Reflectest01 {

    // 体会: 静态性
    public Person getInstance() {
        return new Person();
    }

    // 体会: 反射的动态性
    // 举例1
    public <T> T getInstance(String className) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class clazz = Class.forName(className);
        Constructor cons = clazz.getDeclaredConstructor();
        cons.setAccessible(true);

        return (T) cons.newInstance();
    }

    @Test
    public void test01() throws ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        Person p1 = getInstance();
        System.out.println(p1);

        String className = "com.hejing.反射的应用.Person";
        Person per1 = getInstance(className);
        System.out.println(per1);

        String className1 = "java.util.Date";
        Date date1 = getInstance(className1);
        System.out.println(date1);
    }

    // 体会: 反射的动态性:
    // 举例2:
    public Object invoke(String className, String methodName) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // 1、创建全类名对应的运行时类的对象
        Class clazz = Class.forName(className);

        Constructor con = clazz.getDeclaredConstructor();
        con.setAccessible(true);

        Object obj1 = con.newInstance();

        // 2、获取运行时类中指定的方法，并调用
        Method method = clazz.getDeclaredMethod(methodName);
        method.setAccessible(true);
        return method.invoke(obj1);
    }

    @Test
    public void test02() throws ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        String className = "com.hejing.反射的应用.Person";
        String methodName = "show";
        Object returnValue = invoke(className, methodName);
        System.out.println(returnValue);
    }

}




























